﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using PaperWorld.ORM;
using PaperWorld.IRepository;

namespace PaperWorld.Repository
{
    public class Repository<T> : IRepository<T> where T : class
    {
        protected EntityContainer context;

        public Repository(IDataContext dataContext)
        {
            context = dataContext.GetContext();
        }

        public IEnumerable<T> FindAll()
        {
            return context.Set<T>().ToList();
        }

        public IEnumerable<T> FindAllByPage<TOrderKey>(Expression<Func<T, bool>> filter, Expression<Func<T, TOrderKey>> orderBy, int pageSize, int pageIndex, out int recordsCount)
        {
            recordsCount = context.Set<T>().Where(filter)
                .OrderByDescending(orderBy).Count();
            return context.Set<T>()
                .Where(filter)
                .OrderByDescending(orderBy)
                .Select(t => t)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize);
        }

        public T GetModel(Expression<Func<T, bool>> predicate)
        {
            return context.Set<T>()
                .Where<T>(predicate)
                .FirstOrDefault(predicate);
        }


        public T UpdateModel(T entity)
        {
            return context.Set<T>()
                .Add(entity);
        }

        public int DeleteModel(Expression<Func<T, bool>> predicate)
        {
            context.Set<T>()
                .Remove(GetModel(predicate));
            return 1;
        }
    }
}
